<?php
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
    exit('Access Denied');
}

$table_ad = C::t('#erling_gridad_image#ad_image');
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// 处理表单提交
if(isset($_POST['adsubmit'])) {
    if(!submitcheck('formhash')) {
        cpmsg('提交失败', 'action=plugins&operation=config&do='.$pluginid.'&identifier=erling_gridad_image&pmod=admin_ad_edit','error');
        exit;
    }
    if(!$id && (empty($_POST['uid']) || !isset($_POST['uid']))) {
        cpmsg('请填写用户ID', '', 'error');
    }
    if($id) {
        $current_ad = $table_ad->fetch($id);
        if($current_ad['status'] == 1) {
            $existing_ad = $table_ad->fetch_by_sort_status($_POST['sort'], 1, $id);
            if($existing_ad && $existing_ad['id'] != $id) {
                cpmsg('该位置 '.$_POST['sort'].' 已存在未过期且状态为正常的广告《'.$existing_ad['title'].'》', '', 'error');
            }
        }
    }
    if(empty($_POST['expire_time'])) {
        cpmsg('请设置过期时间', '', 'error');
    }
    
    if(is_numeric($_POST['expire_time'])) {
        $expire_time = intval($_POST['expire_time']);
    } else {
        $expire_time = strtotime($_POST['expire_time']);
        $_POST['expire_time'] = $expire_time;
        if($expire_time === false) {
            cpmsg('无效的过期时间格式', '', 'error');
        }
    }
    if($expire_time < time()) {
        cpmsg('过期时间不能小于当前时间', '', 'error');
    }
    // 过滤数据    // 检查是否包含非法字符
    $pattern = "/[<>\'\"\\\&\x00-\x08\x0b\x0c\x0e-\x1f\$\r\n\t]|\.{2}/";
    $data = array();
    $fields = [
        'title', 'url', 'bgcolor', 'color', 'bold', 'underline', 
        'italic', 'position', 'type', 'sort', 'status', 'expire_time', 'rent_credit'
    ];
    
    foreach($fields as $field) {
        if(isset($_POST[$field]) && $_POST[$field] !== '') {
            if(!in_array($field, ['bold', 'underline', 'italic', 'sort', 'status', 'rent_credit']) && 
               preg_match($pattern, $_POST[$field])) {
                cpmsg($field.'包含非法字符', '', 'error');
            }
            if(in_array($field, ['bold', 'underline', 'italic', 'sort', 'status', 'rent_credit'])) {
                $data[$field] = intval($_POST[$field]);
            } else {
                $data[$field] = daddslashes($_POST[$field]);
            }
        }
    }

    // 图片上传
    if(!empty($_FILES['image']['name'])) {
        $configs_image = C::t('#erling_gridad_image#configs_image');

        $configs = $configs_image->fetch_by_keys([
            'bgimage_on',
            'bgimage_max_size',//kb
            'bgimage_type',
        ]);

        $file = $_FILES['image'];
        $max_size = $configs['bgimage_max_size']['value'] * 1024;

        if($file['size'] > $max_size) {
             cpmsg('图片上传失败: 文件大小超出限制，'.$max_size.'kb', '', 'error');
             exit;
        }
        $bgimage_type = $configs['bgimage_type']['value'];
        $allowed_extensions = explode(',', $bgimage_type);
        $mime_types = [
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif'
        ];
        $allowed_mime_types = [];
        foreach ($allowed_extensions as $ext) {
            if (isset($mime_types[$ext])) {
                $allowed_mime_types[] = $mime_types[$ext];
            }
        }
        $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        if (!in_array($file['type'], $allowed_mime_types) || !in_array($file_ext, $allowed_extensions)) {
            cpmsg('图片上传失败: 文件类型只能是' . $bgimage_type, '', 'error');
            exit;
        }

        $upload_dir = dirname(__FILE__) . '/20cms/upload/';
        if(!is_dir($upload_dir)) {
            if(!mkdir($upload_dir, 0755, true)) {
                cpmsg('图片上传失败: 无法创建上传目录', '', 'error');
                exit;
            }
        }

        $new_name = time() . rand(1000, 9999) . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
        $upload_file = $upload_dir . $new_name;
        if(!move_uploaded_file($file['tmp_name'], $upload_file)) {
            cpmsg('图片上传失败: 上传文件失败', '', 'error');
            exit;
        }
        $data['image'] = 'source/plugin/erling_gridad_image/20cms/upload/' . $new_name;
    }
    
    if($id) {
        $table_ad->update($id, $data);
        cpmsg('广告更新成功', 'action=plugins&operation=config&do='.$pluginid.'&identifier=erling_gridad_image&pmod=admin_ad_list', 'succeed');
    } else {
        $data['uid'] = intval($_POST['uid']);
        $table_ad->insert($data);
        cpmsg('广告添加成功（默认未审核）', 'action=plugins&operation=config&do='.$pluginid.'&identifier=erling_gridad_image&pmod=admin_ad_list', 'succeed');
    }
}

// 获取广告数据
$ad = $id ? $table_ad->fetch($id) : array();

echo '<div class="container">';
echo '<form method="post" action="'.ADMINSCRIPT.'?action=plugins&operation=config&do='.$pluginid.'&identifier=erling_gridad_image&pmod=admin_ad_edit'.($id ? '&id='.$id : '').'"  enctype="multipart/form-data">';
echo '<input type="hidden" name="formhash" value="'.FORMHASH.'" />';

echo '<div class="form-header">';
echo '<h2>'.($id ? '编辑广告' : '添加新广告').'</h2>';
echo '</div>';

echo '<div class="form-group">';
echo '<label>用户id</label>';
echo '<input type="text" name="uid" value="'.dhtmlspecialchars($ad['uid']).'" class="form-input">';
echo '</div>';

echo '<div class="form-group">';
echo '<label>广告标题</label>';
echo '<input type="text" name="title" value="'.dhtmlspecialchars($ad['title']).'" class="form-input">';
echo '</div>';

echo '<div class="form-group">';
echo '<label>链接地址</label>';
echo '<input type="text" name="url" value="'.dhtmlspecialchars($ad['url']).'" class="form-input">';
echo '</div>';

echo '<div class="form-group">';
echo '<label>广告图片</label>';
echo '<input type="file" name="image" class="form-input">';
if(!empty($ad['image'])) {
    echo '<div style="margin-top:10px;"><img src="'.$ad['image'].'" style="max-width:200px;max-height:150px;"></div>';
}
echo '</div>';

echo '<div class="form-group">';
echo '<label>背景颜色</label>';
echo '<input type="text" name="bgcolor" value="'.dhtmlspecialchars($ad['bgcolor']).'" class="form-input color-input">';
echo '<input type="color" value="'.($ad['bgcolor'] ?: '#FFFFFF').'" onchange="this.previousElementSibling.value=this.value" class="color-picker">';
echo '</div>';

echo '<div class="form-group">';
echo '<label>文字颜色</label>';
echo '<input type="text" name="color" value="'.dhtmlspecialchars($ad['color']).'" class="form-input color-input">';
echo '<input type="color" value="'.($ad['color'] ?: '#000000').'" onchange="this.previousElementSibling.value=this.value" class="color-picker">';
echo '</div>';

echo '<div class="form-group">';
echo '<label>文字样式</label>';
echo '<div style="display: flex; gap: 15px;">';
echo '<label><input type="checkbox" name="bold" value="1"'.($ad['bold']?' checked':'').'> 加粗</label>';
echo '<label><input type="checkbox" name="underline" value="1"'.($ad['underline']?' checked':'').'> 下划线</label>';
echo '<label><input type="checkbox" name="italic" value="1"'.($ad['italic']?' checked':'').'> 斜体</label>';
echo '</div>';
echo '</div>';

// echo '<div class="form-group">';
// echo '<label>广告位置</label>';
// echo '<select name="position" class="form-select">';
// echo '<option value="2"'.($ad['position']==2?' selected':'').'>首页头部</option>';
// echo '<option value="3"'.($ad['position']==3?' selected':'').'>首页中部</option>';
// echo '<option value="4"'.($ad['position']==4?' selected':'').'>首页底部</option>';
// echo '<option value="5"'.($ad['position']==5?' selected':'').'>帖子页右侧</option>';
// echo '</select>';
// echo '</div>';

// echo '<div class="form-group">';
// echo '<label>广告类型</label>';
// echo '<select name="type" class="form-select">';
// echo '<option value="grid"'.($ad['type']=='grid'?' selected':'').'>格子广告</option>';
// echo '<option value="banner"'.($ad['type']=='banner'?' selected':'').'>横幅广告</option>';
// echo '</select>';
// echo '</div>';

echo '<div class="form-group">';
echo '<label>排序值</label>';
echo '<input type="text" name="sort" value="'.($id ? intval($ad['sort']) : 1).'" class="form-input">';
echo '</div>';

// echo '<div class="form-group">';
// echo '<label>状态</label>';
// echo '<select name="status" class="form-select">';
// echo '<option value="1"'.($ad['status']==1?' selected':'').'>正常</option>';
// echo '<option value="2"'.($ad['status']==2?' selected':'').'>暂停</option>';
// echo '<option value="3"'.($ad['status']==3?' selected':'').'>未审核</option>';
// echo '<option value="4"'.($ad['status']==4?' selected':'').'>变更后未审核</option>';
// echo '</select>';
// echo '</div>';

echo '<div class="form-group">';
echo '<label>过期时间</label>';
echo '<input type="datetime-local" name="expire_time" value="'.($ad['expire_time'] ? date('Y-m-d\TH:i', $ad['expire_time']) : '').'" class="form-input">';
echo '</div>';

echo '<div class="form-group">';
echo '<label>租金金币</label>';
echo '<input type="text" name="rent_credit" value="'.intval($ad['rent_credit']).'" class="form-input">';
echo '</div>';

echo '<div class="form-footer">';
echo '<button type="submit" name="adsubmit" class="form-submit">提交</button>';
echo '</div>';

echo '</form>';
echo '</div>';

echo '<style>
.form-header { margin-bottom: 20px; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
.form-input, .form-select { width: 100%; padding: 8px; border: 1px solid #DDD; border-radius: 4px; }
.color-input { width: 100px; display: inline-block; }
.color-picker { vertical-align: middle; margin-left: 10px; height: 30px; width: 30px; padding: revert;}
.form-submit { background: #2B73B7; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; }
.form-submit:hover { background: #1E5A8F; }
</style>';